package com.hunttown.common.sharding.client.transaction;

import com.ibatis.sqlmap.client.SqlMapClient;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.CollectionUtils;

public class DefaultMultipleSqlMapClientService implements MultipleSqlMapClientService, ApplicationContextAware, InitializingBean {
    private ApplicationContext springContext;
    private Map<String, Object> sqlMapClientConfig;
    private Map<String, SqlMapClient> sqlMapClientMap;

    public DefaultMultipleSqlMapClientService() {
    }

    public Map<String, SqlMapClient> getSqlMapClients() {
        if (CollectionUtils.isEmpty(this.sqlMapClientMap)) {
            this.sqlMapClientMap = Collections.emptyMap();
        }

        return Collections.unmodifiableMap(this.sqlMapClientMap);
    }

    public void setAllSqlMapClient(Map<String, Object> allSqlMapClient) {
        this.sqlMapClientConfig = allSqlMapClient;
    }

    public void afterPropertiesSet() throws Exception {
        if (CollectionUtils.isEmpty(this.sqlMapClientConfig)) {
            throw new IllegalArgumentException("allSqlMapClient cann't be null or empty!");
        } else {
            this.sqlMapClientMap = new HashMap(this.sqlMapClientConfig.size());
            Iterator i$ = this.sqlMapClientConfig.entrySet().iterator();

            while (i$.hasNext()) {
                Entry<String, Object> entity = (Entry) i$.next();
                Object value = entity.getValue();
                if (value instanceof SqlMapClient) {
                    this.sqlMapClientMap.put(entity.getKey(), (SqlMapClient) value);
                } else {
                    if (!(value instanceof String)) {
                        throw new IllegalArgumentException("illegal value argument,key:" + (String) entity.getKey() + ",a reference or bean name of type sqlMapClient is required!");
                    }

                    Object valueBean = this.springContext.getBean((String) value);
                    if (!(valueBean instanceof PlatformTransactionManager)) {
                        throw new IllegalArgumentException("illegal value argument,key:" + (String) entity.getKey() + ",a reference or bean name of type sqlMapClient is required!");
                    }

                    this.sqlMapClientMap.put(entity.getKey(), (SqlMapClient) valueBean);
                }
            }

        }
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.springContext = applicationContext;
    }
}
